/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uy.edu.ort.as.cliente.igu;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.xml.ws.BindingProvider;
import uy.edu.ort.as.cliente.negocio.EntradaBlog;
import uy.edu.ort.as.cliente.negocio.Tag;
import uy.edu.ort.as.cliente.servicios.ResultadoEntradasBlog;
import uy.edu.ort.as.cliente.servicios.entradablog.EntradaBlogWS;
import uy.edu.ort.as.cliente.servicios.entradablog.EntradaBlogWS_Service;
import uy.edu.ort.as.cliente.util.UtilXML;

/**
 *
 * @author victor
 */
public class JFrameEntradasBlog extends javax.swing.JFrame {
    private SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy/MM/dd");
    private JFramePrincipal fppal;
    
    /**
     * Creates new form JFrameEntradasBlog
     */
    public JFrameEntradasBlog(JFramePrincipal fppal) {
        initComponents();
        this.fppal = fppal;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnEliminar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnAgregar = new javax.swing.JButton();
        lblTitulo = new javax.swing.JLabel();
        btnActualizar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        btnFiltrar = new javax.swing.JToggleButton();
        txtTitulo = new javax.swing.JTextField();
        txtAutor = new javax.swing.JTextField();
        txtFecha = new javax.swing.JTextField();
        txtContenido = new javax.swing.JTextField();
        txtTags = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblItems = new javax.swing.JTable();
        lblResultadoFiltrado = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnEliminar.setLabel("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnEditar.setLabel("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnAgregar.setLabel("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        lblTitulo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTitulo.setText("Entradas de Blog");

        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(102, 102, 102), 1, true));

        btnFiltrar.setText("Filtrar");
        btnFiltrar.setMargin(new java.awt.Insets(2, 2, 2, 2));
        btnFiltrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFiltrarActionPerformed(evt);
            }
        });

        txtContenido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtContenidoActionPerformed(evt);
            }
        });

        jLabel1.setText("título:");

        jLabel2.setText("autor:");

        jLabel3.setText("fecha:");

        jLabel4.setText("contenido:");

        jLabel5.setText("tags:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnFiltrar)
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(txtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(txtAutor, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(txtContenido, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(txtTags))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5)
                        .addComponent(jLabel3)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFiltrar)
                    .addComponent(txtTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtAutor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtContenido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTags, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        tblItems.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Título", "Autor", "Fecha", "Contenido", "Tags"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblItems);

        lblResultadoFiltrado.setForeground(new java.awt.Color(0, 153, 0));
        lblResultadoFiltrado.setText("(resultado filtrado)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 557, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(232, 232, 232)
                                .addComponent(lblTitulo)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnActualizar)
                                .addGap(18, 18, 18)
                                .addComponent(lblResultadoFiltrado)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnAgregar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEditar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnEliminar))
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(lblTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAgregar)
                    .addComponent(btnEditar)
                    .addComponent(btnEliminar)
                    .addComponent(btnActualizar)
                    .addComponent(lblResultadoFiltrado))
                .addContainerGap())
        );

        lblTitulo.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        JFrameAgregarEntradasBlog jfapw = new JFrameAgregarEntradasBlog(fppal, this);
        jfapw.setVisible(true);
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        int indice = tblItems.getSelectedRow();
        if (indice == -1) {
            JOptionPane.showMessageDialog(this, "Seleccione un elemento");
        } else {
            try {
                EntradaBlog entrada = getItem(indice);

                JFrameEditarEntradaBlog jfepw = new JFrameEditarEntradaBlog(fppal, this, indice, entrada);
                jfepw.setVisible(true);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "El valor ingresado para la fecha no es correcto");
            }
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        try {
            eliminar(tblItems);
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "El valor de la fecha del elemento no es correcto");
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        actualizarDatos();
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        actualizarDatos();
    }//GEN-LAST:event_formWindowOpened

    private void btnFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFiltrarActionPerformed
        //actualizarDatos();
    }//GEN-LAST:event_btnFiltrarActionPerformed

    private void txtContenidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtContenidoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtContenidoActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JToggleButton btnFiltrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblResultadoFiltrado;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTable tblItems;
    private javax.swing.JTextField txtAutor;
    private javax.swing.JTextField txtContenido;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtTags;
    private javax.swing.JTextField txtTitulo;
    // End of variables declaration//GEN-END:variables

    private void eliminar(JTable tabla) throws ParseException {
        int indice = tabla.getSelectedRow();
        if (indice == -1) {
            JOptionPane.showMessageDialog(this, "Seleccione un elemento");
        } else {
            int res = JOptionPane.showConfirmDialog(this, "¿Esta seguro que quiere eliminar la entrada de blog?", "¡Atención!", JOptionPane.OK_CANCEL_OPTION);
            if (res == JOptionPane.OK_OPTION) {
                try {
                    EntradaBlog item = getItem(indice);

                    EntradaBlogWS_Service ws = new EntradaBlogWS_Service();
                    EntradaBlogWS port = ws.getEntradaBlogWSPort();
            
                    ((BindingProvider)port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, fppal.getNombreUsuario());
                    ((BindingProvider)port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, fppal.getClaveUsuario());

                    String strRespuesta = port.removerEntradaBlog(UtilXML.parseEntradaBlog(item, true));

                    ResultadoEntradasBlog respuesta = UtilXML.parseResultadoEntradaBlog(strRespuesta, true);

                    if (respuesta.getResultadoCorrecto()) {
                        ((DefaultTableModel) tblItems.getModel()).removeRow(indice);
                        int filas = ((DefaultTableModel) tblItems.getModel()).getRowCount();

                        if (filas > 0) {
                            if (indice < filas) {
                                seleccionarFila(tabla, indice);
                            } else {
                                seleccionarFila(tabla, filas - 1);
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, respuesta.getDescripcion());
                    }
                } catch (Exception exc) {
                    JOptionPane.showMessageDialog(this, exc.getMessage());
                }
            }
        }
    }

    EntradaBlog getItem(int indice) throws ParseException {
        EntradaBlog item = new EntradaBlog();
        
        item.setTitulo(tblItems.getValueAt(indice, 0).toString());
        item.setAutor(tblItems.getValueAt(indice, 1).toString());
        item.setFecha(formatoFecha.parse(tblItems.getValueAt(indice, 2).toString()));
        item.setContenido(tblItems.getValueAt(indice, 3).toString());
        String[] strTags = tblItems.getValueAt(indice, 4).toString().split(";");
        ArrayList<Tag> tags = new ArrayList<>();
        for (String s : strTags) {
            Tag tag = new Tag(s);
            tags.add(tag);
        }
        item.setTags(tags);
        
        return item;
    }

    void seleccionarFila(JTable tabla, int fila) {
        ListSelectionModel selectionModel = tabla.getSelectionModel();
        selectionModel.setSelectionInterval(fila, fila);
    }

    void agregar(EntradaBlog item) {
        DefaultTableModel modelo = (DefaultTableModel)tblItems.getModel();
        String strTags = "";
        for(Tag t : item.getTags()) {
            strTags += (strTags.equals("") ? "" : ";") + t.getValor();
        }
        Object[] row = new Object[]{item.getTitulo(), item.getAutor(), formatoFecha.format(item.getFecha()), item.getContenido(), strTags};
        modelo.addRow(row);
    }

    void editar(int indice, EntradaBlog entrada) {
        DefaultTableModel modelo = (DefaultTableModel)tblItems.getModel();
        modelo.setValueAt(entrada.getTitulo(), indice, 0);
        modelo.setValueAt(entrada.getAutor(), indice, 1);
        modelo.setValueAt(formatoFecha.format(entrada.getFecha()), indice, 2);
        modelo.setValueAt(entrada.getContenido(), indice, 3);
        String strTags = "";
        for(Tag t : entrada.getTags()) {
            strTags += (strTags.equals("") ? "" : ";") + t.getValor();
        }
        modelo.setValueAt(strTags, indice, 4);
    }

    public void actualizarDatos() {
        ((DefaultTableModel)tblItems.getModel()).getDataVector().removeAllElements();
        try {
            EntradaBlogWS_Service ws = new EntradaBlogWS_Service();
            EntradaBlogWS port = ws.getEntradaBlogWSPort();

            ((BindingProvider)port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, fppal.getNombreUsuario());
            ((BindingProvider)port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, fppal.getClaveUsuario());

            String strRespuesta;
            
            if (btnFiltrar.isSelected()) {
                lblResultadoFiltrado.setVisible(true);
                
                EntradaBlog item;
                try {
                    item = getFiltro();
                } catch(ParseException exc) {
                    JOptionPane.showMessageDialog(this, "El valor de fecha introducido no es válido");
                    txtFecha.requestFocusInWindow();
                    return;
                }
                
                strRespuesta = port.buscarEntradaBlog(UtilXML.parseEntradaBlog(item, true));
            } else {
                lblResultadoFiltrado.setVisible(false);
                strRespuesta = port.obtenerTodasEntradasBlog();
            }
            
            ResultadoEntradasBlog respuesta = UtilXML.parseResultadoEntradaBlog(strRespuesta, true);

            if (respuesta.getResultadoCorrecto()) {
                for(EntradaBlog entrada : respuesta.getResultado()) {
                    agregar(entrada);
                }
            } else {
                JOptionPane.showMessageDialog(this, respuesta.getDescripcion());
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }
    
    private EntradaBlog getFiltro() throws ParseException {
        Date fecha;
        
        if (txtFecha.getText().equals("")) {
            fecha = null;
        } else {
            fecha = formatoFecha.parse(txtFecha.getText().trim());
        }

        EntradaBlog item = new EntradaBlog();
        item.setAutor(txtAutor.getText().trim());
        item.setTitulo(txtTitulo.getText().trim());
        item.setContenido(txtContenido.getText());
        item.setFecha(fecha);
        if (!txtTags.getText().equals("")) {
            String[] tags = txtTags.getText().split(";");
            for(String valor : tags) {
                item.getTags().add(new Tag(valor));
            }
        }

        return item;
    }
}
